import re
import random
import yagmail
from odoo import tools
from odoo.addons.basic_configuration.functions.rp_redis_utils import RedisUtils


class Login(object):
    """
    Model:
        登陆验证

    Param:
        - env: odoo env

    Function:
    """

    def __init__(self, env):
        self.env = env

    # 判断同一张表中的重复名称
    def jwt_repeat_datas(self, model, dicts):
        for dict in dicts:
            res = self.env[model].sudo().search([(dict, '=', dicts[dict])])
            if len(res) > 0:
                return False
            else:
                return True

    def jwt_email_format(self, email):
        email_regex = r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$'
        if not re.match(email_regex, email):
            return False
        else:
            return True

    # 发送验证码邮件，并将验证码存入redis中
    def send_verify_code(selk, mail, body):
        rand_num = random.randint(100000, 999999)
        body = body.format(verify_code=rand_num)
        redis_client = RedisUtils()
        remainder_time = redis_client.get_expire_by_second(mail)
        if remainder_time > 240:
            return False
        redis_client.add_str(mail, str(rand_num))
        redis_client.set_expire_by_second(mail, 300)
        return body

    # 邮件发送
    def send_mail_verify(self, act_one, mail):
        rp_email = self.env['rp.email'].search([('act_on', '=', act_one)])
        yag = yagmail.SMTP(user=rp_email.send_mail, password=rp_email.password, host=rp_email.host)
        subject = [rp_email.subject]
        body = tools.html2plaintext(rp_email.template)
        if body.find('{verify_code}') > 0:
            body = self.send_verify_code(mail, body)
            if not body:
                return {'code': 400,
                        'message': '发送失败，发送频率过高'}
        contents = [body]
        yag.send(mail, subject, contents)
        return {'code': 200,
                'message': '发送成功'}

    # 校验验证码
    def verify_mail_code(self, mail, verifyt_code):
        value = RedisUtils().get_str(mail.strip())
        if not value:
            return {
                'code': 400,
                'message': '验证码已失效'
            }
        value = value.decode()
        if value != verifyt_code:
            return {
                'code': 400,
                'message': '验证码不正确'
            }
        else:
            return {
                'code': 200,
                'message': '验证通过'
            }

    # 找回密码
    def find_password(self, info, jwt_utils):
        rp_customer = self.env['rp.customer'].search([('email', '=', info.email)])
        if not rp_customer:
            return {
                'code': 400,
                'message': '该邮箱未绑定用户'
            }
        res = self.verify_mail_code(mail=info.email, verifyt_code=info.verify_code)
        if res.get('code') != 200:
            return res
        if len(info.password) < 6:
            return {'code': 401,
                    'message': '密码要大于6位'}
        if info.password != info.sure_password:
            return {
                'code': 400,
                'message': '两次密码输入不一致'
            }
        password = jwt_utils.encrypt_password(plain_password=info.password)
        rp_customer.write({
            'password': password
        })
        return {
            'code': 200,
            'message': '修改成功'
        }
